'use strict';

const Service = require('egg').Service;

class JobService extends Service {
  // 获取岗位列表（多维度筛选 + 关键词搜索）
  async getJobList({ keyword, status, category, location, enterpriseId, page, pageSize }) {
    const { ctx } = this;
    
    const where = {};
    
    // 企业筛选
    if (enterpriseId) {
      where.enterpriseId = parseInt(enterpriseId);
    }
    
    // 状态筛选
    if (status && status !== 'all') {
      where.jobStatus = status;
    }
    
    // 分类筛选
    if (category && category !== 'all') {
      where.category = category;
    }
    
    // 地点筛选
    if (location && location !== 'all') {
      where.location = location;
    }

    const { count, rows } = await ctx.model.Job.findAndCountAll({
      where,
      include: [
        {
          model: ctx.model.Enterprise,
          as: 'enterprise',
          attributes: ['enterpriseId', 'enterpriseName', 'imageUrl', 'rating']
        }
      ],
      order: [['isTop', 'DESC'], ['createTime', 'DESC']],
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    // 关键词搜索（在后端进行，因为需要跨表搜索）
    let filteredRows = rows;
    if (keyword) {
      const keywordLower = keyword.toLowerCase();
      filteredRows = rows.filter(job => {
        return (
          job.jobName.toLowerCase().includes(keywordLower) ||
          job.jobDescription.toLowerCase().includes(keywordLower) ||
          job.jobRequirements.toLowerCase().includes(keywordLower) ||
          job.enterprise.enterpriseName.toLowerCase().includes(keywordLower)
        );
      });
    }

    return {
      list: filteredRows,
      total: count,
      page,
      pageSize
    };
  }

  // 获取岗位详情
  async getJobDetail(jobId) {
    const { ctx } = this;
    
    const job = await ctx.model.Job.findByPk(jobId, {
      include: [
        {
          model: ctx.model.Enterprise,
          as: 'enterprise'
        }
      ]
    });

    if (!job) {
      throw new Error('岗位不存在');
    }

    // 增加浏览次数
    await job.increment('viewCount');

    return job;
  }

  // 创建岗位
  async createJob(jobData) {
    const { ctx } = this;
    
    jobData.createTime = new Date();
    jobData.updateTime = new Date();
    
    const job = await ctx.model.Job.create(jobData);
    
    // 创建初始统计数据
    await ctx.model.JobStatistics.create({
      jobId: job.jobId,
      statisticsTime: new Date()
    });

    return job;
  }

  // 更新岗位
  async updateJob(jobId, updateData) {
    const { ctx } = this;
    
    const job = await ctx.model.Job.findByPk(jobId);
    if (!job) {
      throw new Error('岗位不存在');
    }

    updateData.updateTime = new Date();
    await job.update(updateData);
    
    return job;
  }

  // 删除岗位
  async deleteJob(jobId) {
    const { ctx } = this;
    
    const job = await ctx.model.Job.findByPk(jobId);
    if (!job) {
      throw new Error('岗位不存在');
    }

    await job.destroy();
  }

  // 更新岗位状态（上线/下线）
  async updateJobStatus(jobId, status) {
    const { ctx } = this;
    
    const job = await ctx.model.Job.findByPk(jobId);
    if (!job) {
      throw new Error('岗位不存在');
    }

    await job.update({
      jobStatus: status,
      updateTime: new Date()
    });

    return job;
  }

  // 更新岗位置顶状态
  async updateJobTopStatus(jobId, isTop) {
    const { ctx } = this;
    
    const job = await ctx.model.Job.findByPk(jobId);
    if (!job) {
      throw new Error('岗位不存在');
    }

    await job.update({
      isTop,
      updateTime: new Date()
    });

    return job;
  }

  // 获取岗位投递数据
  async getJobApplicationData(jobId) {
    const { ctx } = this;
    
    const applications = await ctx.model.JobApplication.findAll({
      where: { jobId },
      order: [['applyTime', 'DESC']]
    });

    const statistics = await ctx.model.JobStatistics.findOne({
      where: { jobId },
      order: [['statisticsTime', 'DESC']]
    });

    return {
      applications,
      statistics
    };
  }

  // 投递岗位
  async applyJob(jobId, applicationData, userId, username) {
    const { ctx } = this;
    
    const job = await ctx.model.Job.findByPk(jobId);
    if (!job) {
      throw new Error('岗位不存在');
    }

    if (job.jobStatus !== 'active') {
      throw new Error('岗位已暂停招聘');
    }

    // 检查是否已经投递过
    const existingApplication = await ctx.model.JobApplication.findOne({
      where: {
        jobId,
        userId
      }
    });

    if (existingApplication) {
      throw new Error('您已经投递过该岗位');
    }

    // 如果提供了简历ID，验证简历是否存在且属于当前用户
    if (applicationData.resumeId) {
      const resume = await ctx.model.Resume.findOne({
        where: {
          id: applicationData.resumeId,
          user_id: userId
        }
      });
      if (!resume) {
        throw new Error('简历不存在或不属于当前用户');
      }
    }

    const application = await ctx.model.JobApplication.create({
      jobId,
      enterpriseId: job.enterpriseId,
      userId,
      userName: username || applicationData.userName,
      resumeId: applicationData.resumeId || null,
      phone: applicationData.phone,
      email: applicationData.email,
      coverLetter: applicationData.coverLetter || null,
      applyTime: new Date()
    });

    // 更新岗位投递次数
    await job.increment('applicationCount');

    // 更新统计数据
    await this.updateJobStatistics(jobId);

    return application;
  }

  // 收藏岗位
  // 收藏岗位
  async collectJob(jobId, userId) {
    const { ctx } = this;
    
    try {
      // 检查岗位是否存在
      const job = await ctx.model.Job.findByPk(jobId);
      if (!job) {
        throw new Error('岗位不存在');
      }

      // 检查是否已收藏
      const existing = await ctx.model.Favorite.findOne({
        where: {
          user_id: userId,
          job_id: jobId
        }
      });

      if (existing) {
        throw new Error('该岗位已在收藏列表中');
      }

      // 创建收藏记录
      await ctx.model.Favorite.create({
        user_id: userId,
        job_id: jobId,
        job_info: JSON.stringify(job),
        created_at: new Date(),
        updated_at: new Date()
      });

      console.log(`✅ 用户 ${userId} 收藏了岗位 ${jobId}`);
      return { success: true, message: '收藏成功' };
    } catch (error) {
      console.error('收藏岗位失败:', error);
      throw error;
    }
  }

  // 取消收藏岗位
  async uncollectJob(jobId, userId) {
    const { ctx } = this;
    
    try {
      const deleted = await ctx.model.Favorite.destroy({
        where: {
          user_id: userId,
          job_id: jobId
        }
      });

      if (deleted === 0) {
        throw new Error('收藏记录不存在');
      }

      console.log(`✅ 用户 ${userId} 取消收藏了岗位 ${jobId}`);
      return { success: true, message: '取消收藏成功' };
    } catch (error) {
      console.error('取消收藏失败:', error);
      throw error;
    }
  }

  // 获取用户收藏的岗位列表
  async getUserFavoriteJobs({ userId, page, pageSize }) {
    const { ctx } = this;
    
    try {
      const { count, rows } = await ctx.model.Favorite.findAndCountAll({
        where: {
          user_id: userId
        },
        include: [
          {
            model: ctx.model.Job,
            as: 'favoriteJob',
            include: [
              {
                model: ctx.model.Enterprise,
                as: 'enterprise',
                attributes: ['enterpriseName', 'imageUrl']
              }
            ]
          }
        ],
        order: [['created_at', 'DESC']],
        limit: pageSize,
        offset: (page - 1) * pageSize
      });

      return {
        list: rows,
        total: count,
        page,
        pageSize
      };
    } catch (error) {
      console.error('获取收藏列表失败:', error);
      throw error;
    }
  }

  // 检查岗位是否已收藏
  async checkJobCollected(jobId, userId) {
    const { ctx } = this;
    
    try {
      const favorite = await ctx.model.Favorite.findOne({
        where: {
          user_id: userId,
          job_id: jobId
        }
      });

      return { collected: !!favorite };
    } catch (error) {
      console.error('检查收藏状态失败:', error);
      throw error;
    }
  }

  // 获取用户投递记录
  async getUserApplications({ userId, status, page, pageSize }) {
    const { ctx } = this;
    
    const where = { userId };
    if (status && status !== 'all') {
      where.status = status;
    }

    const { count, rows } = await ctx.model.JobApplication.findAndCountAll({
      where,
      include: [
        {
          model: ctx.model.Job,
          as: 'job',
          include: [
            {
              model: ctx.model.Enterprise,
              as: 'enterprise',
              attributes: ['enterpriseName', 'imageUrl']
            }
          ]
        },
        {
          model: ctx.model.Resume,
          as: 'resume',
          attributes: ['id', 'resume_name'],
          required: false // 左连接，即使没有关联的简历也返回记录
        }
      ],
      order: [['applyTime', 'DESC']],
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    // 处理返回数据，添加 resumeName 字段
    const processedRows = rows.map(row => {
      const data = row.toJSON();
      // 如果有关联的简历，使用简历名称；否则使用默认值
      data.resumeName = data.resume ? data.resume.resume_name : '在线简历';
      return data;
    });

    return {
      list: processedRows,
      total: count,
      page,
      pageSize
    };
  }

  // 获取企业的投递记录
  async getEnterpriseApplications({ enterpriseId, status, page, pageSize }) {
    const { ctx } = this;
    const { Op } = ctx.app.Sequelize;
    
    // 构建查询条件
    const where = {};
    if (status && status !== 'all') {
      where.status = status;
    }
    
    // 查询该企业下所有岗位的投递记录
    const { count, rows } = await ctx.model.JobApplication.findAndCountAll({
      where,
      include: [
        {
          model: ctx.model.Job,
          as: 'job',
          where: { enterpriseId: parseInt(enterpriseId) }, // 筛选该企业的岗位
          include: [
            {
              model: ctx.model.Enterprise,
              as: 'enterprise',
              attributes: ['enterpriseName', 'imageUrl']
            }
          ]
        },
        {
          model: ctx.model.Resume,
          as: 'resume',
          attributes: ['id', 'resume_name'],
          required: false // 左连接，即使没有关联的简历也返回记录
        },
        {
          model: ctx.model.User,
          as: 'user',
          attributes: ['id', 'username', 'avatar'],
          required: false // 左连接，获取用户信息
        }
      ],
      order: [['applyTime', 'DESC']],
      limit: pageSize,
      offset: (page - 1) * pageSize
    });

    // 处理返回数据，添加 resumeName 和 username 字段
    const processedRows = rows.map(row => {
      const data = row.toJSON();
      // 如果有关联的简历，使用简历名称；否则使用默认值
      data.resumeName = data.resume ? data.resume.resume_name : '在线简历';
      // 添加用户名
      data.username = data.user ? data.user.username : `用户${data.userId}`;
      return data;
    });

    return {
      list: processedRows,
      total: count,
      page,
      pageSize
    };
  }

  // 批量操作岗位
  async batchOperateJobs(jobIds, operation) {
    const { ctx } = this;
    
    const updateData = { updateTime: new Date() };
    
    switch (operation) {
      case 'online':
        updateData.jobStatus = 'active';
        break;
      case 'offline':
        updateData.jobStatus = 'inactive';
        break;
      case 'top':
        updateData.isTop = true;
        break;
      case 'untop':
        updateData.isTop = false;
        break;
      case 'delete':
        await ctx.model.Job.destroy({
          where: { jobId: jobIds }
        });
        return { success: true };
      default:
        throw new Error('不支持的操作');
    }

    await ctx.model.Job.update(updateData, {
      where: { jobId: jobIds }
    });

    return { success: true };
  }

  // 撤回投递
  async withdrawApplication(applicationId) {
    const { ctx } = this;
    
    const application = await ctx.model.JobApplication.findByPk(applicationId);
    if (!application) {
      throw new Error('投递记录不存在');
    }

    // 只有待处理状态的投递才能撤回
    if (application.status !== 'pending') {
      throw new Error('只有待处理状态的投递才能撤回');
    }

    // 删除投递记录
    await application.destroy();

    // 更新岗位投递次数
    const job = await ctx.model.Job.findByPk(application.jobId);
    if (job) {
      await job.decrement('applicationCount');
      // 更新统计数据
      await this.updateJobStatistics(application.jobId);
    }

    return { success: true };
  }

  // 更新投递状态
  async updateApplicationStatus(applicationId, status) {
    const { ctx } = this;
    
    const application = await ctx.model.JobApplication.findByPk(applicationId);
    if (!application) {
      throw new Error('投递记录不存在');
    }

    // 更新状态
    await application.update({ status });

    console.log(`✅ 投递记录 ${applicationId} 状态已更新为: ${status}`);

    return { 
      success: true, 
      applicationId,
      status 
    };
  }

  // 更新岗位统计数据
  async updateJobStatistics(jobId) {
    const { ctx } = this;
    
    const applicationCount = await ctx.model.JobApplication.count({
      where: { jobId }
    });

    const job = await ctx.model.Job.findByPk(jobId);
    const viewCount = job.viewCount || 0;

    // 更新或创建统计数据
    await ctx.model.JobStatistics.upsert({
      jobId,
      applicationCount,
      viewCount,
      interviewCount: 0,
      hireCount: 0,
      statisticsTime: new Date()
    });
  }
}

module.exports = JobService;










































